//
//  SearchOrderViewController.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-27.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "SearchOrderViewController.h"
#import "SearchOrderInputViewController.h"
#import "CustomNavigationController.h"
#import "InputViewController.h"
#import "SearchResultViewController.h"
#import "CONSTS.h"

@interface SearchOrderViewController()

- (void)inputViewAnimation:(NSInteger)row_;

@end

@implementation SearchOrderViewController
@synthesize tableView                                   =               _tableView;
@synthesize customNavigationController                  =               _customNavigationController;

- (void)dealloc 
{
    setStartDate( nil );
    [_tableView release];
    LF_RELEASE_SAFELY(_customNavigationController);
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"搜索订单";
}

- (void)viewDidUnload
{
    [self setTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}



#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *cellIdentifier0 = @"starDate";
    static NSString *cellIdentifier1 = @"endDate";
    static NSString *cellIdentifier2 = @"orderStatus";
    static NSString *cellIdentifier3 = @"nick";
    static NSString *cellIdentifier4 = @"type";
    static NSString *cellIdentifier5 = @"rateStatus";
    
    UITableViewCell *cell = nil;
    
    NSInteger row = [indexPath row];
    if (0 == row)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier0];
        if (cell == nil) 
        {
            NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
            cell = [cellArray objectAtIndex: row];
            
            NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
            [dateFormatter setDateFormat: @"yyyy-MM-dd"];
            
            NSDate *date = [[NSDate date] dateByAddingTimeInterval: -(60 * 60 * 24)];
            // setStartDate([date retain]);
            NSString *dateStr = [dateFormatter stringFromDate: date];
            
            UILabel *label = (UILabel *)[cell viewWithTag: 101];
            label.text = dateStr;
            
        }
    }else if (1 == row)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];
        if (cell == nil) 
        {
            NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
            cell = [cellArray objectAtIndex: row];
            
            NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
            [dateFormatter setDateFormat: @"yyyy-MM-dd"];
            
            NSDate *date = [NSDate date];
            NSString *dateStr = [dateFormatter stringFromDate: date];
            
            UILabel *label = (UILabel *)[cell viewWithTag: 101];
            label.text = dateStr;
        }
    }else if (2 == row)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier2];
        if (cell == nil) 
        {
            NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
            cell = [cellArray objectAtIndex: row];
        }
    }else if (3 == row)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier3];
        if (cell == nil) 
        {
            NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
            cell = [cellArray objectAtIndex: row];
        }
    }else if (4 == row)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier4];
        if (cell == nil) 
        {
            NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
            cell = [cellArray objectAtIndex: row];
        }
    }else if (5 == row)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier5];
        if (cell == nil) 
        {
            NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
            cell = [cellArray objectAtIndex: row];
        }
    }else if (6 == row)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier5];
        if (cell == nil) 
        {
            NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
            cell = [cellArray objectAtIndex: row];
            
            UIButton *searchButton = (UIButton *)[cell viewWithTag: 101];
            [searchButton addTarget: self action: @selector(search) forControlEvents: UIControlEventTouchUpInside];
        }
    }
    
    
    
    return cell;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    NSInteger row = [indexPath row];
    if (0 == row)   //开始时间
    {
        NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
        cell = [cellArray objectAtIndex: row];
        
        return cell.frame.size.height;
        
    }else if (1 == row) //结束时间
    {
        NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
        cell = [cellArray objectAtIndex: row];
        
        return cell.frame.size.height;
        
    }else if (2 == row)
    { 
        NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
        cell = [cellArray objectAtIndex: row];
        
        return cell.frame.size.height;
        
    }else if (3 == row)
    {
        NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
        cell = [cellArray objectAtIndex: row];
        
        return cell.frame.size.height;
        
    }else if (4 == row)
    {
        NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
        cell = [cellArray objectAtIndex: row];
        
        return cell.frame.size.height;
        
    }else if (5 == row)
    {
        NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
        cell = [cellArray objectAtIndex: row];
        
        return cell.frame.size.height;
        
    }else if (6 == row)
    {
        NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"SearchOrderCell" owner: nil options: nil];
        cell = [cellArray objectAtIndex: row];
        
        return cell.frame.size.height;
        
    }
    
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath: indexPath animated: YES];
    
    NSInteger row = [indexPath row];
    
    [self inputViewAnimation: row];
    
}

#pragma mark - 自定义函数
- (void)inputViewAnimation:(NSInteger)row_
{
    LFInputViewLayout layout = 0;
    if (0 == row_)
    {
        layout = LFInputViewLayoutForPickDate;
        
    }else if (1 == row_)
    {
        layout = LFInputViewLayoutForPickDate;
        
        
    }else if (2 == row_)
    { 
        
        layout = LFInputViewLayoutForOrderStatus;
        
    }else if (3 == row_)
    {
        InputViewController *inputViewController = [[[InputViewController alloc] initWithDelegate: self 
                                                                                             sign: @"nick" 
                                                                                       titleLabel: @"请输入买家昵称" 
                                                                                   finishInputSel: @selector(nickIsFinished:sign:)] autorelease]; 
        
        inputViewController.navigationItem.title = @"筛选条件";
        
        self.customNavigationController = [[[CustomNavigationController alloc] initWithRootViewController: inputViewController] autorelease];
        
        _customNavigationController.view.frame = CGRectMake(0, -_customNavigationController.view.frame.size.height,  320,  _customNavigationController.view.frame.size.height);
        
        [self.view.window addSubview: _customNavigationController.view];
        
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationDuration: 0.3];
        [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
        
        
        self.customNavigationController.view.frame = CGRectMake(0, 0,  320, _customNavigationController.view.frame.size.height);
        
        [UIView commitAnimations];
        
        
        return;
        
    }else if (4 == row_)
    {
        
        layout = LFInputViewLayoutForOrderStatus;
        
        
        
    }else if (5 == row_)
    {
        layout = LFInputViewLayoutForOrderStatus;
        
    }
    
    SearchOrderInputViewController *searchOrderInputViewController = [[[SearchOrderInputViewController alloc] initWithDelegate: self  layout: layout row: row_] autorelease];
    searchOrderInputViewController.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    
    [self.navigationController presentModalViewController: searchOrderInputViewController animated: YES];
}

- (void)nickIsFinished:(NSString *)nick_ sign:(id)sign_
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow: 3 inSection: 0];
    
    UITableViewCell *cell = [_tableView cellForRowAtIndexPath: indexPath];
    UILabel *nickLabel = (UILabel *)[cell viewWithTag: 101];
    nickLabel.text = nick_;
}

- (void)search
{
    /*
     fields	Field List	必须	total_fee		 需要返回的字段。目前支持有：
     1. Trade中可以指定返回的fields:
     seller_nick, buyer_nick, title, type, created, tid, seller_rate, buyer_rate, status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, pic_path, num_iid, num, price, cod_fee, cod_status, shipping_type, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone，seller_flag 
     2. Order中可以指定返回fields：orders.title, orders.pic_path, orders.price, orders.num, orders.num_iid, orders.sku_id, orders.refund_status, orders.status, orders.oid, orders.total_fee, orders.payment, orders.discount_fee, orders.adjust_fee, orders.sku_properties_name, orders.item_meal_name, orders.buyer_rate, orders.seller_rate, orders.outer_iid, orders.outer_sku_id, orders.refund_id, orders.seller_type 
     3. fields：orders（返回2中Order的所有内容）
     
     
     start_created	Date	可选	2000-01-01 00:00:00		 查询三个月内交易创建时间开始。格式:yyyy-MM-dd HH:mm:ss
     
     end_created	Date	可选	2000-01-01 23:59:59		 查询交易创建时间结束。格式:yyyy-MM-dd HH:mm:ss
     
     status	String	可选	ALL_WAIT_PAY		 交易状态，默认查询所有交易状态的数据，除了默认值外每次只能查询一种状态。 可选值： TRADE_NO_CREATE_PAY(没有创建支付宝交易) WAIT_BUYER_PAY(等待买家付款) WAIT_SELLER_SEND_GOODS(等待卖家发货,即:买家已付款) WAIT_BUYER_CONFIRM_GOODS(等待买家确认收货,即:卖家已发货) TRADE_BUYER_SIGNED(买家已签收,货到付款专用) TRADE_FINISHED(交易成功) TRADE_CLOSED(交易关闭) TRADE_CLOSED_BY_TAOBAO(交易被淘宝关闭) ALL_WAIT_PAY(包含：WAIT_BUYER_PAY、TRADE_NO_CREATE_PAY) ALL_CLOSED(包含：TRADE_CLOSED、TRADE_CLOSED_BY_TAOBAO)
     
     buyer_nick	String	可选	zhangsan		 买家昵称
     
     type	String	可选	game_equipment		 交易类型列表，同时查询多种交易类型可用逗号分隔。默认同时查询guarantee_trade, auto_delivery, ec, cod的4种交易类型的数据 。 可选值： fixed(一口价) auction(拍卖) guarantee_trade(一口价、拍卖) independent_simple_trade(旺店入门版交易) independent_shop_trade(旺店标准版交易) auto_delivery(自动发货) ec(直冲) cod(货到付款) game_equipment(游戏装备) shopex_trade(ShopEX交易) netcn_trade(万网交易) external_trade(统一外部交易) instant_trade (即时到账) b2c_cod(大商家货到付款) hotel_trade(酒店类型交易) super_market_trade(商超交易) super_market_cod_trade(商超货到付款交易)
     
     rate_status	String	可选	RATE_UNBUYER		 评价状态，默认查询所有评价状态的数据，除了默认值外每次只能查询一种状态。
     可选值： RATE_UNBUYER(买家未评) RATE_UNSELLER(卖家未评) RATE_BUYER_UNSELLER(买家已评，卖家未评) RATE_UNBUYER_SELLER(买家未评，卖家已评)
     
     tag	String	可选	time_card		 卖家对交易的自定义分组标签，目前可选值为：time_card（点卡软件代充），fee_card（话费软件代充）
     
     page_no	Number	可选	1		 页码。取值范围:大于零的整数; 默认值:1
     
     page_size	Number	可选	40		 每页条数。取值范围:大于零的整数; 默认值:40;最大值:100
     */
    
    NSMutableDictionary *pDic = [NSMutableDictionary dictionary];
    
    NSString *fields = @"tid,orders.title,orders.oid,orders.pic_path,orders.num_iid";
    [pDic setObject: fields forKey: @"fields"];
    
    NSIndexPath *indexPath = nil;
    UITableViewCell *cell = nil;
    UILabel *label = nil;
    
    //开始时间
    //格式:yyyy-MM-dd HH:mm:ss
    indexPath = [NSIndexPath indexPathForRow: 0 inSection:0];
    cell = [_tableView cellForRowAtIndexPath: indexPath];
    label = (UILabel *)[cell viewWithTag: 101];
    NSString *start_created = [label.text stringByAppendingString: @" 00:00:00"];
    [pDic setObject: start_created forKey: @"start_created"];
    
    //结束时间
    indexPath = [NSIndexPath indexPathForRow: 1 inSection:0];
    cell = [_tableView cellForRowAtIndexPath: indexPath];
    label = (UILabel *)[cell viewWithTag: 101];
    NSString *end_created = [label.text stringByAppendingString: @" 00:00:00"];
    [pDic setObject: end_created forKey: @"end_created"];
    
    //订单状态
    indexPath = [NSIndexPath indexPathForRow: 2 inSection: 0];
    cell = [_tableView cellForRowAtIndexPath: indexPath];
    label = (UILabel *)[cell viewWithTag: 101];
    if (![label.text isEqualToString: BU_XIAN])
    {
        NSString *status = getOrderStatusStrByStatus(label.text);
        [pDic setObject: status forKey: @"status"];
    }
    
    //买家昵称
    indexPath = [NSIndexPath indexPathForRow: 3 inSection:0];
    cell = [_tableView cellForRowAtIndexPath: indexPath];
    label = (UILabel *)[cell viewWithTag: 101];
    if (label.text && ![label.text isEqualToString: @""])
    {
        NSString *buyer_nick = label.text;
        [pDic setObject: buyer_nick forKey: @"buyer_nick"];
    }
    
    //交易类型
    indexPath = [NSIndexPath indexPathForRow: 4 inSection:0];
    cell = [_tableView cellForRowAtIndexPath: indexPath];
    label = (UILabel *)[cell viewWithTag: 101];
    if (![label.text isEqualToString: BU_XIAN])
    {
        NSString *type = getOrderTypeByStr(label.text);
        [pDic setObject: type forKey: @"type"];
    }else
    {
        //默认同时查询guarantee_trade, auto_delivery, ec, cod的4种交易类型的数据,所以要改为所有类型
        NSString *type = [[[NSString alloc] initWithFormat: @"%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@", 
                           @"fixed",
                           @"auction",
                           @"guarantee_trade",
                           @"independent_simple_trade",
                           @"independent_shop_trade",
                           @"auto_delivery",
                           @"ec",
                           @"cod",
                           @"game_equipment",
                           @"shopex_trade",
                           @"netcn_trade",
                           @"external_trade",
                           @"instant_trade",
                           @"b2c_cod",
                           @"hotel_trade",
                           @"super_market_trade",
                           @"super_market_cod_trade"] autorelease];;
        [pDic setObject: type forKey: @"type"];
    }
    
    //评价状态
    indexPath = [NSIndexPath indexPathForRow: 5 inSection:0];
    cell = [_tableView cellForRowAtIndexPath: indexPath];
    label = (UILabel *)[cell viewWithTag: 101];
    if (label.text && ![label.text isEqualToString: @""] && ![label.text isEqualToString: BU_XIAN])
    {
        NSString *rate_status = getRateStatusBy(label.text);
        [pDic setObject: rate_status forKey: @"rate_status"];
    }
    
    
    SearchResultViewController *searchResultViewController = [[[SearchResultViewController alloc] initWithPDic: pDic] autorelease];
    [self.navigationController pushViewController: searchResultViewController animated: YES];
}

#pragma  mark - LFInputViewLayoutDelegate
- (void)layout:(id)object row:(NSInteger)row_
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow: row_ inSection: 0];
    UITableViewCell *cell = [_tableView cellForRowAtIndexPath: indexPath];
    
    UILabel *label = (UILabel *)[cell viewWithTag: 101];
    label.text = (NSString *)object;
}
@end
